package com.foreveross.bsl.plugin;

import android.util.Log;
import android.widget.Toast;

import com.foreveross.bsl.util.Preferences;
import com.foreveross.chameleon.CpushModule;
import com.foreveross.chameleon.activity.MainActivity;
import com.foreveross.push.socket.PushSetup;
import com.foss.AppLog;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;

import java.sql.SQLOutput;

/**
 * Created by zhouzhineng on 14-7-29.
 */
public class PushPlugin extends CordovaPlugin{
    public final static String TAG = "PushPlugin";

    public final static String ACTION_START_PUSH_SERVICE = "start_push_service";
    public final static String ACTION_STOP_PUSH_SERVICE = "stop_push_service";

    @Override
    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
        if(!Preferences.getPushPluginLaunch()) {
            startPush();
        }
        super.initialize(cordova, webView);
    }

    @Override
    public boolean execute(String action,String args, CallbackContext callbackContext) throws JSONException {
        System.out.println("push plugin");
        if(action.equals(ACTION_START_PUSH_SERVICE)) {
            startPush();
        } else if(action.equals(ACTION_STOP_PUSH_SERVICE)) {
            stopPush();
        }
        return super.execute(action, args, callbackContext);
    }

    public void startPush() {
        //System.out.println("推送服务开启................");
        Log.e("PushPlugin","推送服务开启................");
        if(CpushModule.getCpushModule() != null) {
            CpushModule.getCpushModule().startService();
            Preferences.savePushPluginLaunch(true);
        }
    }

    public void stopPush() {
        //System.out.println("推送服务关闭................");
        Log.e("PushPlugin","推送服务关闭................");
        CpushModule.getCpushModule().stopService();
        String userName = PushSetup.getInstance().getUserName();
        if(!"guest".equals(userName)) {
            Preferences.saveCurrentUserName("guest");
            PushSetup.getInstance().startSetup("PushService退出，要求以guest 身份连接push服务器", false, false);
        } else {
            AppLog.i("PushService, 已用guest 登录");
        }
        Preferences.savePushPluginLaunch(false);
    }

}
